/**
 * API client for external service communication.
 */

import axios, { AxiosInstance, AxiosResponse } from 'axios';

export interface APIResponse<T = any> {
  data: T;
  status: number;
  statusText: string;
}

export class APIClient {
  private httpClient: AxiosInstance;
  private baseURL: string;

  constructor(baseURL: string, apiKey?: string) {
    this.baseURL = baseURL.replace(/\/$/, '');
    
    this.httpClient = axios.create({
      baseURL: this.baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
        ...(apiKey && { 'Authorization': `Bearer ${apiKey}` })
      }
    });

    // Add request interceptor
    this.httpClient.interceptors.request.use(
      (config) => {
        console.log(`Making ${config.method?.toUpperCase()} request to ${config.url}`);
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // Add response interceptor
    this.httpClient.interceptors.response.use(
      (response) => {
        return response;
      },
      (error) => {
        console.error('API request failed:', error.message);
        return Promise.reject(error);
      }
    );
  }

  async getData<T = any>(endpoint: string): Promise<APIResponse<T>> {
    const url = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
    const response: AxiosResponse<T> = await this.httpClient.get(url);
    
    return {
      data: response.data,
      status: response.status,
      statusText: response.statusText
    };
  }

  async postData<T = any, U = any>(endpoint: string, data: U): Promise<APIResponse<T>> {
    const url = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
    const response: AxiosResponse<T> = await this.httpClient.post(url, data);
    
    return {
      data: response.data,
      status: response.status,
      statusText: response.statusText
    };
  }

  async uploadFile<T = any>(endpoint: string, filePath: string): Promise<APIResponse<T>> {
    const fs = await import('fs');
    const FormData = (await import('form-data')).default;
    
    const url = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
    const form = new FormData();
    form.append('file', fs.createReadStream(filePath));
    
    const response: AxiosResponse<T> = await this.httpClient.post(url, form, {
      headers: {
        ...form.getHeaders(),
      },
    });
    
    return {
      data: response.data,
      status: response.status,
      statusText: response.statusText
    };
  }

  async putData<T = any, U = any>(endpoint: string, data: U): Promise<APIResponse<T>> {
    const url = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
    const response: AxiosResponse<T> = await this.httpClient.put(url, data);
    
    return {
      data: response.data,
      status: response.status,
      statusText: response.statusText
    };
  }

  async deleteData<T = any>(endpoint: string): Promise<APIResponse<T>> {
    const url = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
    const response: AxiosResponse<T> = await this.httpClient.delete(url);
    
    return {
      data: response.data,
      status: response.status,
      statusText: response.statusText
    };
  }

  updateApiKey(apiKey: string): void {
    this.httpClient.defaults.headers['Authorization'] = `Bearer ${apiKey}`;
  }

  close(): void {
    // Cleanup if needed
  }
}